import { api } from "@/api";
import { useMyContext } from "@/hooks";
import action from "@/store/action";
import { Icon } from "@iconify/react";
import { Tag } from "antd";
import { useEffect, useMemo, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import styled from "styled-components";

const Styled = styled.div`
  display: flex;
  justify-content: center;
  margin-bottom: 5rem;
  .btn {
    margin-left: 10px;
    font-size: 5rem;
    padding: 2rem 5rem;
    display: flex;
    align-items: center;
  }
`;

const Reward = ({ articleId, likeCount }) => {
  const dispatch = useDispatch();
  const { messageApi } = useMyContext();
  const { appStore, userStore } = useSelector((state) => {
    return {
      appStore: state.app,
      userStore: state.user,
    };
  });
  const [count, setCount] = useState(likeCount);

  const isLike = useMemo(() => {
    return userStore.userInfo.articleLikeSet.includes(articleId);
  }, [userStore.userInfo.articleLikeSet.length]);

  const likeArticle = async () => {
    // 判断是否登录
    if (!userStore.userInfo.id) {
      dispatch(action.app.setLoginFlag(true));
      messageApi.info("请先登录！");
      return;
    }
    try {
      await api.saveLikeArticle(articleId);
      if (userStore.userInfo.articleLikeSet.includes(articleId)) {
        setCount(count - 1);
        messageApi.info("已取消");
      } else {
        setCount(count + 1);
        messageApi.info("已点赞");
      }
      //维护全局数据
      dispatch(action.user.articleLike(articleId));
    } catch (error) {}
  };

  useEffect(() => {
    setCount(likeCount);
  }, [likeCount]);
  return (
    <Styled>
      <Tag
        className="btn"
        color={isLike ? "success" : "default"}
        onClick={likeArticle}
      >
        <Icon icon="icon-park-outline:good-one" /> 点赞{count}
      </Tag>
      <Tag
        className="btn"
        color="processing"
        onClick={() => messageApi.info("该功能暂未开通")}
      >
        <Icon icon="ic:baseline-qrcode" /> 打赏
      </Tag>
    </Styled>
  );
};

export default Reward;
